const Controller = require('egg').Controller;

class AddrController extends Controller {
  // 查找
  async index() {
    const { ctx, app } = this;
    let result = await ctx.service.addr.getAll();
    console.log(result);
    if (result) {
      ctx.body = {
        code: 1,
        result
      }
    } else {
      ctx.body = {
        code: 0, msg: "暂无数据"
      }
    }
  }
  // 添加
  async create() {
    const { ctx, app } = this;
    console.log(ctx.myparams);
    let { username, city, address, mobile, tell, email } = ctx.myparams;
    // 校验参数
    if (!username || !city || !address || !mobile || !tell || !email) {
      ctx.status = 403;
      ctx.body = { code: 0, msg: "参数缺失" }
      return;
    }
    let obj = {...ctx.myparams,is_default: 0,}
    const result = await ctx.service.addr.add(obj);
    if (result.affectedRows == 1) {
      ctx.body = { code: 1, msg: "添加成功" }
    } else { ctx.body = { code: 0, msg: "添加失败" } }
  }
  // 编辑
  async update() {
    const { ctx, app } = this;
    console.log(ctx.myparams);
    let { username, city, address, mobile, is_default, tell, email, id } = ctx.myparams;
    let obj = { username, city, address, mobile, is_default, tell, email, id: id * 1 }
    const result = await ctx.service.addr.edit(obj)
    if (result.affectedRows == 1) {
      ctx.body = { code: 1, msg: "编辑成功" }
    } else { ctx.body = { code: 0, msg: "编辑失败" } }

  }

  // 设置默认地址
  async createDefault() {
    const { ctx, app } = this
    console.log(ctx.myparams);
    const result = await ctx.service.addr.setDefault(ctx.myparams)
    console.log(result);
    if (result.affectedRows == 1) {
      ctx.body = { code: 1, msg: "默认地址设置成功" }
    } else { ctx.status = 500, ctx.body = { code: 0, msg: "默认地址设置失败" } }
  }
  // 删除
  async destroy() {
    const { ctx, app } = this;
    console.log(ctx.myparams);
    const result = await ctx.service.addr.del(ctx.myparams);
    if (result.affectedRows == 1) {
      ctx.body = { code: 1, msg: "删除成功" }
    } else { ctx.body = { code: 0, msg: "删除失败" } }
  }
}

module.exports = AddrController;